<?php

namespace register\controller;

//require_once("./register/view/RegisterUserView.php");
require_once("./register/model/RegisterModel.php");
//require_once("./login/view/LoginView.php");

class RegisterController {
	
	private $view;
	private $model;
	
	private $username;
	private $password;
	
	public function __construct(\register\view\RegisterUserView $registerView,
								\login\view\LoginView $loginView) {
		$this->view = $registerView;
		$this->loginView = $loginView;
		$this->model = new \register\model\RegisterModel($this->view);
	}
	
	public function doRegisterUser() {
		if ($this->view->isRegisteringUser()) {			
			try {
				$username = $this->model->createUsername($this->view->getUsername());
				$this->model->userAlreadyExists($username);
				$password = $this->model->createPassword($this->view->getPassword());
				$otherPassword = $this->model->createPassword($this->view->getOtherPassword());
				$this->model->isPasswordsSame($password, $otherPassword);
				
				$user = $this->model->createUser($username, $password);
				$this->model->saveUser($user);
				$this->model->showUserWasRegisteredMessage();
				$this->model->setSessionUsername($username->__toString());
				$this->view->RegisterOK();
			}
			catch (\Exception $e) {
				\Debug::log("Register user failed", false, $e->getMessage());
				$this->view->RegisterFailed($e->getMessage());
			}
		}
		
	}
}